package com.atgion.manager.config.service;

import cn.hutool.core.util.ObjectUtil;
import com.atgion.manager.mapper.SysResourceMapper;

import com.atgion.common.log.utils.SecurityUtil;
import com.atgion.exception.exception.GlobalException;
import com.atgion.exception.exception.GlobalExceptionEnum;
import com.atgion.exception.util.ExceptionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Service;
//import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

/**
 * 权限处理器
 */
@Slf4j
@Service("pre")
//@Controller("pre")
// 将该类注册为控制层，确保GlobalExceptionHandler类中的@ExceptionHandler(GlobalException.class)起作用
public class PermissionService {

    /**
     * 所有权限标识
     */
    private static final String ALL_PERMISSION = "*:*:*";
    
    @Autowired
    private SysResourceMapper sysResourceMapper;

    public Boolean hasPermission(String... permissions) {
        if (ObjectUtil.isEmpty(permissions)) {
            return false;
        }
        
        try {
            // 获取当前用户的所有权限
            List<String> perms = SecurityUtil.getUserDetails().getAuthorities().stream()
                    .map(GrantedAuthority::getAuthority).toList();
            
            // 判断当前用户的所有权限是否包含接口上定义的权限
            boolean hasAuth = perms.contains(ALL_PERMISSION) || 
                    Arrays.stream(permissions).anyMatch(perms::contains);
                    
            // 如果缓存中的权限判断失败，尝试从数据库直接检查权限
            if (!hasAuth) {
                Long userId = SecurityUtil.getSysUser().getId();
                // 遍历所有权限，找到一个满足的即可
                for (String permission : permissions) {
                    Integer count = sysResourceMapper.checkUserPermission(userId, permission);
                    if (count != null && count > 0) {
                        log.info("用户{}权限{}在数据库中验证通过", userId, permission);
                        return true;
                    }
                }
                ExceptionUtil.throwEx(GlobalExceptionEnum.ERROR_NO_PERMISSION);
                // 这里不应该有 return 语句，因为上面已经抛出异常
                // return hasAuth; 
            }
            return hasAuth;
        } catch (Exception e) {
            log.error("权限检查发生错误: {}", e.getMessage(), e);
            throw new GlobalException(e.getMessage());
        }
    }
}
